package com.nchu.commondevelopmentframework.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nchu.commondevelopmentframework.entity.Menu;
import com.nchu.commondevelopmentframework.mapper.MenuMapper;
import com.nchu.commondevelopmentframework.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @className: MenuServiceImpl
 * @description: 菜单实体Service实现类
 * @author: Li Chuanwei
 * @date: 2024/02/20 14:05
 * @Company: Copyright [日期] by [作者或个人]
 **/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService<Menu> {
    @Autowired
    private MenuMapper menuMapper;


    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户Id
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectMenusByUser(Long userId) {
        List<Menu> menus = menuMapper.selectMenusByUserId(userId);
        return getChildPerms(menus, 0);
    }

    /**
     * 查询全部菜单
     *
     * @return 全部菜单列表
     */
    @Override
    public List<Menu> selectAllMenus() {
        List<Menu> menus = menuMapper.selectAllMenus();
        return getChildPerms(menus, 0);
    }


    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<Menu> getChildPerms(List<Menu> list, int parentId)
    {
        List<Menu> returnList = new ArrayList<Menu>();
        for (Iterator<Menu> iterator = list.iterator(); iterator.hasNext();)
        {
            Menu t = (Menu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<Menu> list, Menu t)
    {
        // 得到子节点列表
        List<Menu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Menu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Menu> getChildList(List<Menu> list, Menu t)
    {
        List<Menu> tlist = new ArrayList<Menu>();
        Iterator<Menu> it = list.iterator();
        while (it.hasNext())
        {
            Menu n = (Menu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Menu> list, Menu t)
    {
        return getChildList(list, t).size() > 0;
    }
}
